package com.jy.service.impl;

import com.jy.common.*;
import com.jy.dao.UserDao;
import com.jy.model.Department;
import com.jy.model.Menu;
import com.jy.model.User;
import com.jy.service.UserInfoService;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Component
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserDao userDao;

    /**
     * @return
     */
    public int insertTale() {
        List<User> user = userDao.selectTable();
        return 1;
    }

    public String getUser(User user,HttpSession session) throws ServiceException {
        MD5 md5 = new MD5();
        user.setPassword(md5.getMD5ofStr(user.getPassword()));
        User users = userDao.getUser(user);
        if (users == null) {
            throw new ServiceException("用户名密码错误");
        } else {
            session.setAttribute(SessionInfo.SessionName, users);
            //SessionListener.sessionContext.getSessionMap().remove(session.getId());
            HttpSession userSession =(HttpSession)SessionListener.sessionContext.getSessionMap().get(users.getId());
           System.out.println("session.getId()"+session.getId());

            if(userSession!=null&&!userSession.getId().equals(session.getId())){
                System.out.println("userSession.getId():"+userSession.getId());
                SessionListener.sessionContext.getSessionMap().remove(userSession.getId());
            }
            SessionListener.sessionContext.getSessionMap().put(users.getId(),session);//用户和session
            SessionListener.sessionContext.getSessionMap().put(session.getId(), session);//sessionid和session

           // HttpSession ss=sessionHandlerByCacheMap(usersession);
            return JSONObject.fromObject(users).toString();
        }
    }
    private String sessionHandlerByCacheMap(HttpSession session)
    {
        // TODO Auto-generated method stub
        User uy=(User) session.getAttribute(SessionInfo.SessionName);
        HttpSession userSession=null;
        String userid=uy.getId();
        String msg=null;
        System.out.println(SessionListener.sessionContext.getSessionMap().get(userid));
        if(SessionListener.sessionContext.getSessionMap().get(userid)!=null){
             userSession =(HttpSession)SessionListener.sessionContext.getSessionMap().get(userid);
            //注销在线用户
            if(userSession!=null&&!userSession.getId().equals(session.getId())){
                //SessionListener.sessionContext.getSessionMap().remove(userid);
                SessionListener.sessionContext.getSessionMap().remove(session.getId());
               msg="您的账号已经在另一处登录，您被迫下线！";
                // userSession.invalidate();
            }
            /*SessionListener.sessionContext.getSessionMap().remove(userid);
            //清除在线用户后，更新map,替换map sessionid
            SessionListener.sessionContext.getSessionMap().remove(session.getId());
            SessionListener.sessionContext.getSessionMap().put(userid,session);//用户和session
            if (session != null) {
                SessionListener.sessionContext.getSessionMap().put(session.getId(), session);//sessionid和session
            }*/
        }
        /*else
        {
            // 根据当前sessionid 取session对象。 更新map key=用户名 value=session对象 删除map
            SessionListener.sessionContext.getSessionMap().get(session.getId());
            SessionListener.sessionContext.getSessionMap().put(userid,SessionListener.sessionContext.getSessionMap().get(session.getId()));
            SessionListener.sessionContext.getSessionMap().remove(session.getId());
        }*/
        return msg;
    }
    @Override
    public String saveUser(User user) {
        String uuid = UUIDUtils.getUUID();
        user.setId(uuid);
        user.setPassword(MD5.toMD5(user.getPassword()));
        userDao.saveUser(user);
        return uuid;
    }

    @Override
    public List<Department> getDepartment(String dept, String flag, String fatherId) {
        return userDao.getDepartment(dept, flag, fatherId);
    }

    public List<User> searchUser(String searchUser) {
        return userDao.searchUser(searchUser);
    }

    @Override
    public User getUserInfo(String token) {
        return userDao.getUserInfo(token);
    }

    @Override
    public void processActivate(String code, String mail) throws ServiceException,ParseException {
        User user = userDao.findMailUser(mail);
        if (user != null) {
            //验证用户激活
            if (user.getIsjh() == 0) {
                //验证是否过期
                if (isGq(user.getCodetime())) {
                    //验证激活码是否正确
                    if(user.getCode().equals(code)){
                        userDao.updateCode(user.getId());
                        throw new ServiceException("激活成功");
                    }else{
                        throw new ServiceException("激活码不正确");
                    }
                }else {
                    throw new ServiceException("激活码已过期");
                }
            } else {
                throw new ServiceException("邮箱已激活，请登录");
            }
        } else {
            throw new ServiceException("该邮箱未注册（邮箱地址不存在）");
        }
    }

    @Override
    public void sendupdate(String mail) {
        User user = userDao.findMailUser(mail);
        if(user!=null){
            SendEmail.send(mail,user.getCode(),"toModifyPwd");
        }
    }



    @Override
    public void modifyPwd(String mail, String code,String password) throws ServiceException {
        User user = userDao.findUserPwd(mail,code);
        if(user!=null){
            int flg=userDao.updateUserPwd(mail,code,MD5.toMD5(password));
            if(flg>0){
                throw new ServiceException("修改成功");
            }else{
                throw new ServiceException("邮箱验证失败，请重新发送邮件");
            }
        } else {
            throw new ServiceException("邮箱验证失败，请重新发送邮件");
        }
    }

    @Override
    public void validateReg(User user) throws ServiceException {
        int flg=userDao.getCheckUser(user.getUsername());
        if(flg>0){
            throw new ServiceException("用户名已存在");
        }else{
            int mail=userDao.getCheckUserMail(user.getMailbox());
            if(mail>0){
                throw new ServiceException("邮箱已存在");
            }

        }
    }

    public boolean isGq(String codetime) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d HH:mm:ss");

        Date start = sdf.parse(codetime);

        Date end = sdf.parse(DateUtils.formatDateByFormat(new Date(),"yyyy-M-d HH:mm:ss"));

        long cha = end.getTime() - start.getTime();

        if (cha < 0) {

            return false;

        }

        double result = cha * 1.0 / (1000 * 60 * 60);
        System.out.println(result);
        if (result <= 24) {

            return true;

        } else {

            return false;

        }
    }
    public List<Menu> menulist(String userid){
        return userDao.menulist(userid);
    }
}
